/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.monitor;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.star.framework.monitor.annotation.MonitorMethod;
import cn.star.framework.monitor.annotation.MonitorMethod.Null;
import cn.star.framework.monitor.core.IMonitorInvoke;
import cn.star.framework.monitor.MonitorInvokeProxy.InvokeType;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.ApplicationContext;

/**
 * 上下文信息<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
@Slf4j
public class MonitorContext {

  /** {@link ProceedingJoinPoint} */
  private final JoinPoint delegate;

  @Getter private MonitorMethod monitor;

  /** 主方法方法执行结果 */
  @Getter @Setter private Object methodResult;

  /** 主方法方法参数列表 */
  @Getter private Object methodParameter;

  /** 主方法所在类的引用实例 */
  @Getter
  @SuppressWarnings("all")
  private Object $this;

  /**
   * 主方法执行耗时(毫秒)<br>
   * 默认：-1，标识未记录耗时
   */
  @Getter @Setter private long durationInMillis = -1;

  @Getter private List<MonitorType> monitorTypes;

  /** 主方法 */
  @Getter private Method method;

  /** 实例 */
  private final Map<InvokeType, Class<? extends IMonitorInvoke>> monitorInvokeMap;

  public MonitorContext(JoinPoint delegate) {
    this.delegate = delegate;
    this.monitorInvokeMap = new HashMap<>(4);
    this.monitorTypes = new ArrayList<>();

    this.init();
  }

  private void init() {
    try {
      MethodSignature signature = (MethodSignature) delegate.getSignature();
      Method method = signature.getMethod();
      MonitorMethod monitor = method.getAnnotation(MonitorMethod.class);

      if (monitor != null) {
        if (ArrayUtil.isNotEmpty(monitor.types())) {
          this.monitorTypes = Arrays.asList(monitor.types());
        }
        this.addInvokeInstance(InvokeType.BEFORE, monitor.before());
        this.addInvokeInstance(InvokeType.BEFORE_ASYNC, monitor.beforeAsync());
        this.addInvokeInstance(InvokeType.AFTER, monitor.after());
        this.addInvokeInstance(InvokeType.AFTER_ASYNC, monitor.afterAsync());
      }

      this.method = method;
      this.monitor = monitor;
      this.methodParameter = delegate.getArgs();
      this.$this = delegate.getThis();
    } catch (Exception e) {
      log.warn("Exception occurred while initializing the context, {}", e.getMessage());
    }
  }

  private void addInvokeInstance(InvokeType type, Class<? extends IMonitorInvoke> clazz) {
    if (Null.class != clazz && clazz != null) {
      this.monitorInvokeMap.put(type, clazz);
    }
  }

  public IMonitorInvoke getMonitorInvoke(InvokeType type) {
    Class<? extends IMonitorInvoke> clazz = monitorInvokeMap.get(type);
    return this.getMonitorInvoke(clazz == null ? Null.class : clazz);
  }

  public IMonitorInvoke getMonitorInvoke(ApplicationContext context, InvokeType type) {
    Class<? extends IMonitorInvoke> clazz = monitorInvokeMap.get(type);
    if (context != null && clazz != null) {
      try {
        return context.getBean(clazz);
      } catch (Exception e) {
        // 忽略异常
      }
    }
    return this.getMonitorInvoke(type);
  }

  public String getMethodName() {
    return method == null ? null : method.getName();
  }

  @SuppressWarnings("all")
  private IMonitorInvoke getMonitorInvoke(Class<? extends IMonitorInvoke> clazz) {
    return ReflectUtil.newInstance(clazz);
  }
}
